
/**
 * @Title: UploadSgsServiceImpl.java
 * @Package com.py.credit.service.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2020
 * Company:金电联行(江苏)信息技术有限公司
 * @author Comsys-jdzc
 * @date 2020年10月20日 上午10:06:49
 * @version V1.0
 */

package com.py.credit.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.py.credit.dao.UploadSgsDao;

import com.py.credit.entity.RespEntity;

import com.py.credit.entity.SubmitXzcfBean;

import com.py.credit.entity.SubmitXzxkBean;
import com.py.credit.entity.Table;
import com.py.credit.service.UploadSgsService;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.UuidUtil;

import cn.hutool.json.JSONArray;

/**
 * @ClassName: UploadSgsServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author jdzc
 * @date 2020年10月20日 上午10:06:49
 *
 */
@Service
public class UploadSgsServiceImpl implements UploadSgsService {

	@Autowired
	private UploadSgsDao UploadSgsdao;

	@Override
	public Object run(int type, String sys_method, String access_key, String secret_key) throws Exception {
		String request_id = UuidUtil.getInstance().getUUid();
		String business_id = "";
		String tableName = "";
		if (type == 0) {
			tableName = "t_1000000010001_3ioj4gezqu";
			business_id ="e5b0975222ef45d08b5d0d7254b0000f";
			// 获取需要推送数据
			List<SubmitXzxkBean> datalist = UploadSgsdao.getFrXzXkList();
			if (datalist.isEmpty()) {
				return "暂无需要推送数据";
			}
			JSONObject jsonobject = new JSONObject();
			jsonobject.put("request_id", request_id);
			jsonobject.put("access_key", access_key);
			jsonobject.put("business_id", business_id);
			jsonobject.put("secret_key", secret_key);
			jsonobject.put("data", datalist);
			String jsonStr = JSONObject.toJSONString(jsonobject);
			String resp = postForEntity(sys_method, jsonStr);
			// String resp
			// ="{\"code\":0,\"msg\":null,\"count\":0,\"data\":\"{\\\"msg\\\":\\\"业务规则验证失败\\\",\\\"code\\\":\\\"004\\\",\\\"cost_time\\\":\\\"66\\\",\\\"description\\\":\\\"本次共接收到3条数据，其中0条正确数据成功入库，3条错误数据入库问题表。\\\",\\\"error_data\\\":[{\\\"check_status\\\":\\\"1\\\",\\\"cost_time\\\":0,\\\"description\\\":\\\"
			// 字段“许可类别(XK_XKLB)”不能为空；\\\\n\\\",\\\"errorObjectDescription\\\":{\\\"XK_XKLB\\\":\\\"字段“许可类别”(XK_XKLB)不能为空；\\\"},\\\"params\\\":{\\\"AREA_ID\\\":\\\"110108\\\",\\\"IS_SHARE\\\":0,\\\"XK_XDR_LB\\\":\\\"0\\\",\\\"XK_XKBH\\\":\\\"顺安监危化项目安设审字〔2019〕0001号\\\",\\\"GATHER_TYPE\\\":2,\\\"CREDIT_CODE\\\":\\\"911101131025365782\\\",\\\"QYZCH\\\":\\\"\\\",\\\"OBJECT_TYPE\\\":\\\"2\\\",\\\"SWDJ\\\":\\\"\\\",\\\"SJC\\\":\\\"20201021150548\\\",\\\"XK_YXQZ\\\":\\\"20190323000000\\\",\\\"XK_LYDWDM\\\":\\\"11110110765014703U\\\",\\\"XK_LYDW\\\":\\\"北京市顺义区安全生产监督管理局\\\",\\\"YW_ID\\\":\\\"1918\\\",\\\"OBJECT_ID\\\":\\\"\\\",\\\"IS_REPAIR\\\":0,\\\"ERROR_MEG\\\":\\\"
			// 字段“许可类别(XK_XKLB)”不能为空；\\\\n\\\",\\\"XK_XKWS\\\":\\\"危险化学品建设项目安全审查书\\\",\\\"BZ\\\":\\\"\\\",\\\"XK_XKJGDM\\\":\\\"11110110765014703U\\\",\\\"IS_DEL\\\":0,\\\"XK_XDR_SYDW\\\":\\\"\\\",\\\"ID\\\":\\\"2da17d484996493c8c4af05e4f768c25\\\",\\\"CREATE_TIME\\\":\\\"20201021150548\\\",\\\"XK_FR_ZJHM\\\":\\\"\\\",\\\"DJZT\\\":\\\"1\\\",\\\"DEPT_ID\\\":\\\"XCQCZJ\\\",\\\"BUSINESS_ID\\\":\\\"164170036032456892792f63a31a85ad\\\",\\\"XK_FR_ZJLX\\\":\\\"\\\",\\\"IS_EXPIRE\\\":0,\\\"XK_NR\\\":\\\"中国石化销售有限公司北京顺义顺煤加油站贯标改造项目\\\",\\\"XK_FRDB\\\":\\\"曹楷雨\\\",\\\"IS_RELEASE\\\":0,\\\"XK_YXQZI\\\":\\\"20220323000000\\\",\\\"BEGIN_TIME\\\":\\\"20190323000000\\\",\\\"XK_XKLB\\\":\\\"\\\",\\\"OBJECT_NAME\\\":\\\"中国石化销售有限公司北京顺义顺煤加油站\\\",\\\"XKWJBH\\\":\\\"顺安监危化项目受字〔2019〕0001号\\\",\\\"XK_XKZS\\\":\\\"危险化学品建设项目安全设施设计审查意见书\\\",\\\"XK_XDR_SHZZ\\\":\\\"\\\",\\\"ID_NUM\\\":\\\"\\\",\\\"CERTIFICATE_TYPE\\\":\\\"\\\",\\\"XK_XKJG\\\":\\\"北京市顺义区安全生产监督管理局\\\"}},{\\\"check_status\\\":\\\"1\\\",\\\"cost_time\\\":0,\\\"description\\\":\\\"
			// 该条数据已通过其他方式进行对接，记录已存在数据库；\\\\n\\\",\\\"errorObjectDescription\\\":{},\\\"params\\\":{\\\"AREA_ID\\\":\\\"110108\\\",\\\"IS_SHARE\\\":0,\\\"XK_XDR_LB\\\":\\\"0\\\",\\\"XK_XKBH\\\":\\\"京顺安经字[2018]000039\\\",\\\"GATHER_TYPE\\\":2,\\\"CREDIT_CODE\\\":\\\"911101131025374822\\\",\\\"QYZCH\\\":\\\"\\\",\\\"OBJECT_TYPE\\\":\\\"2\\\",\\\"SWDJ\\\":\\\"\\\",\\\"SJC\\\":\\\"20201021150548\\\",\\\"XK_YXQZ\\\":\\\"20190329000000\\\",\\\"XK_LYDWDM\\\":\\\"11110110765014703U\\\",\\\"XK_LYDW\\\":\\\"北京市顺义区安全生产监督管理局\\\",\\\"YW_ID\\\":\\\"1919\\\",\\\"OBJECT_ID\\\":\\\"\\\",\\\"IS_REPAIR\\\":0,\\\"ERROR_MEG\\\":\\\"
			// 该条数据已通过其他方式进行对接，记录已存在数据库；\\\\n\\\",\\\"XK_XKWS\\\":\\\"北京市危险化学品经营许可证申请批准通知书\\\",\\\"BZ\\\":\\\"\\\",\\\"XK_XKJGDM\\\":\\\"11110110765014703U\\\",\\\"IS_DEL\\\":0,\\\"XK_XDR_SYDW\\\":\\\"\\\",\\\"ID\\\":\\\"5ebcd007e31041578530108a35cbac1a\\\",\\\"CREATE_TIME\\\":\\\"20201021150548\\\",\\\"XK_FR_ZJHM\\\":\\\"\\\",\\\"DJZT\\\":\\\"1\\\",\\\"DEPT_ID\\\":\\\"XCQCZJ\\\",\\\"BUSINESS_ID\\\":\\\"164170036032456892792f63a31a85ad\\\",\\\"XK_FR_ZJLX\\\":\\\"\\\",\\\"IS_EXPIRE\\\":0,\\\"XK_NR\\\":\\\"汽油、柴油[闭杯闪点≤60℃]\\\",\\\"XK_FRDB\\\":\\\"曹楷雨\\\",\\\"IS_RELEASE\\\":0,\\\"XK_YXQZI\\\":\\\"20191010000000\\\",\\\"BEGIN_TIME\\\":\\\"20190329000000\\\",\\\"XK_XKLB\\\":\\\"1\\\",\\\"OBJECT_NAME\\\":\\\"中国石化销售有限公司北京顺义航润加油站\\\",\\\"XKWJBH\\\":\\\"京顺危化经许证送字〔2019〕0008号\\\",\\\"XK_XKZS\\\":\\\"危险化学品经营许可证\\\",\\\"XK_XDR_SHZZ\\\":\\\"\\\",\\\"ID_NUM\\\":\\\"\\\",\\\"CERTIFICATE_TYPE\\\":\\\"\\\",\\\"XK_XKJG\\\":\\\"北京市顺义区安全生产监督管理局\\\"}},{\\\"check_status\\\":\\\"1\\\",\\\"cost_time\\\":0,\\\"description\\\":\\\"
			// 该条数据已通过其他方式进行对接，记录已存在数据库；\\\\n\\\",\\\"errorObjectDescription\\\":{},\\\"params\\\":{\\\"AREA_ID\\\":\\\"110108\\\",\\\"IS_SHARE\\\":0,\\\"XK_XDR_LB\\\":\\\"0\\\",\\\"XK_XKBH\\\":\\\"京顺安经字[2018]000036\\\",\\\"GATHER_TYPE\\\":2,\\\"CREDIT_CODE\\\":\\\"91110113801741562G\\\",\\\"QYZCH\\\":\\\"\\\",\\\"OBJECT_TYPE\\\":\\\"2\\\",\\\"SWDJ\\\":\\\"\\\",\\\"SJC\\\":\\\"20201021150548\\\",\\\"XK_YXQZ\\\":\\\"20190314000000\\\",\\\"XK_LYDWDM\\\":\\\"11110110765014703U\\\",\\\"XK_LYDW\\\":\\\"北京市顺义区安全生产监督管理局\\\",\\\"YW_ID\\\":\\\"1920\\\",\\\"OBJECT_ID\\\":\\\"\\\",\\\"IS_REPAIR\\\":0,\\\"ERROR_MEG\\\":\\\"
			// 该条数据已通过其他方式进行对接，记录已存在数据库；\\\\n\\\",\\\"XK_XKWS\\\":\\\"北京市危险化学品经营许可证申请批准通知书\\\",\\\"BZ\\\":\\\"\\\",\\\"XK_XKJGDM\\\":\\\"11110110765014703U\\\",\\\"IS_DEL\\\":0,\\\"XK_XDR_SYDW\\\":\\\"\\\",\\\"ID\\\":\\\"8c378ac88e3045f98a86444b596607af\\\",\\\"CREATE_TIME\\\":\\\"20201021150548\\\",\\\"XK_FR_ZJHM\\\":\\\"\\\",\\\"DJZT\\\":\\\"1\\\",\\\"DEPT_ID\\\":\\\"XCQCZJ\\\",\\\"BUSINESS_ID\\\":\\\"164170036032456892792f63a31a85ad\\\",\\\"XK_FR_ZJLX\\\":\\\"\\\",\\\"IS_EXPIRE\\\":0,\\\"XK_NR\\\":\\\"煤油、甲基叔丁基醚、石脑油、二甲苯异构体混合物、苯、汽油、柴油[闭杯闪点≤60℃]、乙醇[无水]、变性乙醇、乙醇汽油\\\",\\\"XK_FRDB\\\":\\\"晏永\\\",\\\"IS_RELEASE\\\":0,\\\"XK_YXQZI\\\":\\\"20191025000000\\\",\\\"BEGIN_TIME\\\":\\\"20190314000000\\\",\\\"XK_XKLB\\\":\\\"1\\\",\\\"OBJECT_NAME\\\":\\\"北京中油华富石油化工有限责任公司\\\",\\\"XKWJBH\\\":\\\"京顺危化经许证送字〔2019〕0005号\\\",\\\"XK_XKZS\\\":\\\"危险化学品经营许可证\\\",\\\"XK_XDR_SHZZ\\\":\\\"\\\",\\\"ID_NUM\\\":\\\"\\\",\\\"CERTIFICATE_TYPE\\\":\\\"\\\",\\\"XK_XKJG\\\":\\\"北京市顺义区安全生产监督管理局\\\"}}]}\"}";
			
			// 保存返回数据
			this.saveSubmitLogs(type, resp, datalist, null, tableName);
			return resp;
		} else if (type == 1) {
			tableName = "t_1000010010003_vVwjDLoDWy";
			business_id ="e5b0975222ef45d08b5d0d7254b0000f";
			// 获取需要推送数据
			List<SubmitXzxkBean> datalist = UploadSgsdao.getZrrXzXkList();
			if (datalist.isEmpty()) {
				return "暂无需要推送数据";
			}
			JSONObject jsonobject = new JSONObject();
			jsonobject.put("request_id", request_id);
			jsonobject.put("access_key", access_key);
			jsonobject.put("business_id", business_id);
			jsonobject.put("secret_key", secret_key);
			jsonobject.put("data", datalist);
			String jsonStr = JSONObject.toJSONString(jsonobject);
			String resp = postForEntity(sys_method, jsonStr);

			// 保存返回数据
			this.saveSubmitLogs(type, resp, datalist, null, tableName);
			return resp;
		} else if (type == 2) {
			tableName = "t_1000000010002_xsni4zszp0";
			business_id ="01249d89f37d4936b0ae2e7a909c876d";
			// 获取需要推送数据
			List<SubmitXzcfBean> datalist = UploadSgsdao.getFrXzCfList();
			if (datalist.isEmpty()) {
				return "暂无需要推送数据";
			}
			JSONObject jsonobject = new JSONObject();
			jsonobject.put("request_id", request_id);
			jsonobject.put("access_key", access_key);
			jsonobject.put("business_id", business_id);
			jsonobject.put("secret_key", secret_key);
			jsonobject.put("data", datalist);
			String jsonStr = JSONObject.toJSONString(jsonobject);
			String resp = postForEntity(sys_method, jsonStr);
			
			// 保存返回数据
			this.saveSubmitLogs(type, resp, null, datalist, tableName);
			return resp;
		} else if (type == 3) {
			tableName = "t_1000010010004_kfpulzpf7d";
			business_id ="01249d89f37d4936b0ae2e7a909c876d";
			// 获取需要推送数据
			List<SubmitXzcfBean> datalist = UploadSgsdao.getZrrXzCfList();
			if (datalist.isEmpty()) {
				return "暂无需要推送数据";
			}
			JSONObject jsonobject = new JSONObject();
			jsonobject.put("request_id", request_id);
			jsonobject.put("access_key", access_key);
			jsonobject.put("business_id", business_id);
			jsonobject.put("secret_key", secret_key);
			jsonobject.put("data", datalist);
			String jsonStr = JSONObject.toJSONString(jsonobject);
			String resp = postForEntity(sys_method, jsonStr);
			
			// 保存返回数据
			this.saveSubmitLogs(type, resp, null, datalist, tableName);
			return resp;
		}

		return null;

	}

	/**
	 * @Title: saveSubmitLogs @Description: TODO(这里用一句话描述这个方法的作用) @param @param
	 * type @param @param resp @param @param object @param @param list @param @param
	 * tableName 设定文件 @return void 返回类型 @throws
	 */

	private void saveSubmitLogs(int type, String resp, List<SubmitXzxkBean> xzxkList, List<SubmitXzcfBean> xzcfList,
			String tableName) {
		
		// 保存上报记录信息及明细信息
		DateUtil dataUtil = DateUtil.getInstance();
		String batNo = "BN" + UuidUtil.getInstance().getUUid();
		String subDate = dataUtil.getCurrDate(DateUtil.YYYY_MM_DD);

		
		// 原数据的recordIds 集合
		List<String> recordIds = new ArrayList<String>();
		if (type == 0 || type == 1) {// 行政许可
			//recordIds = xzxkList.stream().map(SubmitXzxkBean -> SubmitXzxkBean.getYW_ID()).collect(Collectors.toList());
		} else {// 行政处罚
		//	recordIds = xzcfList.stream().map(SubmitXzcfBean -> SubmitXzcfBean.getYW_ID()).collect(Collectors.toList());
		}

		RespEntity logsInfo = JSON.toJavaObject(JSONObject.parseObject(resp), RespEntity.class);
		logsInfo.setBatNo(batNo);
		logsInfo.setSubDate(subDate);
		logsInfo.setType(type);
		logsInfo.setTableName(tableName);
		String error_data = logsInfo.getError_data().toString();
		UploadSgsdao.addInfo(logsInfo, error_data);
		JSONObject jsonObject = JSONObject.parseObject(resp);
	
			List<Object> list = logsInfo.getError_data();
			for (Object obj : list) {
				JSONObject jo = JSONObject.parseObject(obj.toString());
				JSONObject params = JSONObject.parseObject(jo.get("params").toString());
				String record_id = params.getString("YW_ID");
				String description = jo.getString("description");
				UploadSgsdao.saveSubmitLogsDetails(record_id, description, params.toJSONString(), batNo);
			}
	
		

		UploadSgsdao.updateXzStatusByRecordIds(tableName, recordIds);// 需改原数据的状态
	}

	/**
	 * 请求体形式 传json参数
	 * 
	 * @param url
	 *            请求路径
	 * @param jsonParam
	 *            json参数
	 * @return
	 * @throws Exception
	 */
	public static String postForEntity(String url, String jsonParam) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient client = HttpClients.createDefault();
		String respContent = null;
		StringEntity entity = new StringEntity(jsonParam, "utf-8");// 解决中文乱码问题
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");

		httpPost.setEntity(entity);
		HttpResponse resp = client.execute(httpPost);
		if (resp.getStatusLine().getStatusCode() == 200) {
			HttpEntity he = resp.getEntity();
			respContent = EntityUtils.toString(he, "UTF-8");
		} else {
			InputStream inputStream = null;
			ByteArrayOutputStream result = null;
			try {
				inputStream = resp.getEntity().getContent();
				result = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length;
				while ((length = inputStream.read(buffer)) != -1) {
					result.write(buffer, 0, length);
				}
				String s = result.toString("UTF-8");
				throw new Exception(s);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (inputStream != null) {
					inputStream.close();
				}
				if (result != null) {
					result.close();
				}
			}
		}
		return respContent;
	}

	public static void main(String[] args) {
		String res = "{\"code\":0,\"msg\":null,\"count\":0,\"data\":\"{\\\"msg\\\":\\\"成功\\\",\\\"code\\\":\\\"200\\\",\\\"cost_time\\\":\\\"100\\\",\\\"description\\\":\\\"本次共接收到3条数据，其中3条正确数据成功入库，0条错误数据入库问题表。\\\",\\\"error_data\\\":[]}\"}";
		JSONObject jsonObject = JSONObject.parseObject(res);

		System.out.println(jsonObject.get("data"));
		RespEntity user = JSON.toJavaObject(JSONObject.parseObject(jsonObject.get("data").toString()),
				RespEntity.class);
		List<Object> list = user.getError_data();
		for (Object obj : list) {
			JSONObject jo = JSONObject.parseObject(obj.toString());

			JSONObject params = JSONObject.parseObject(jo.get("params").toString());
			System.out.println(params);
			System.out.println(params.get("YW_ID"));
		}

	}

	
	
	@Override
	public void updatePushStatus(Integer tableId,Integer record_id) {
		 // 获取数据表信息
        String tablename = UploadSgsdao.queryCubeById(tableId);
		UploadSgsdao.updatePushStatus("t_"+tablename,record_id);
	}
	
	

}
